﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using YiSha.Data.Repository;
using YiSha.Entity.Test;
using YiSha.Model.Param.Test;
using YiSha.Util.Extension;

namespace YiSha.Service.Test
{
    public class ScheduleService : RepositoryFactory
    {

        #region 获取数据
        public async Task<List<ScheduleEntity>> GetListJson(ScheduleParam param)
        {
            var expression = ListFilter(param);

            // 优化逻辑：根据是否需要第一条数据，直接在查询阶段限制
            if (param.FetchFirst == true)
            {
                // 数据库层面只查第一条，减少数据传输和内存占用
                var firstItem = await this.BaseRepository().FindEntity(expression);
                return firstItem != null ? new List<ScheduleEntity> { firstItem } : new List<ScheduleEntity>();
            }
            else
            {
                // 正常查询所有符合条件的数据
                var list = await this.BaseRepository().FindList(expression);
                return list.ToList();
            }
        }
        #endregion

        #region 提交数据
        public async Task<ScheduleEntity> Insert(ScheduleEntity entity)
        {
            entity.RealNumber = -1;
            // 执行插入操作
            await this.BaseRepository().Insert(entity);
            return entity; // 返回包含自增ID的实体
        }

        public async Task<ScheduleEntity> Update(ScheduleEntity entity)
        {
            await entity.Modify();
            // 执行更新操作
            await this.BaseRepository().Update(entity);
            return entity; 
        }
        #endregion

        #region 私有方法
        private Expression<Func<ScheduleEntity, bool>> ListFilter(ScheduleParam param)
        {
            var expression = LinqExtensions.True<ScheduleEntity>();

            // 如果传入了排产日期，则根据排产日期筛选
            if (param.Date.HasValue)
            {
                expression = expression.And(t => t.Date == param.Date.Value);
            }

            // 如果传入了工令号，则根据工令号筛选
            if (!string.IsNullOrEmpty(param.WorkOrderNumber))
            {
                expression = expression.And(t => t.WorkOrderNumber == param.WorkOrderNumber);
            }

            // 如果传入了工序Id，则根据工序Id筛选
            if (param.ProcessId.HasValue)
            {
                expression = expression.And(t => t.ProcessId == param.ProcessId.Value);
            }

            // 如果传入了工序Id数组，则根据工序Id数组筛选
            if (!param.ProcessIds.IsEmpty())
            {
                expression = expression.And(t => param.ProcessIds.Contains(t.ProcessId));
            }

            return expression;
        }
        #endregion

    }
}
